// 华为云OCR服务文件
const tokenManager = require('./token-manager.js')

class HuaweiOCRService {
  constructor() {
    this.config = {
      projectId: '05bfa947f88025502f62c00ea658fd4f',
      apiUrl: 'https://ocr.cn-north-4.myhuaweicloud.com'
    }
  }

  // 华为云OCR识别
  async recognizeText(imageBase64) {
    try {
      console.log('开始OCR识别，图片大小:', imageBase64.length)
      return await this.callRealHuaweiOCR(imageBase64)
    } catch (error) {
      console.error('华为云OCR识别失败:', error)
      throw error
    }
  }

  // 获取华为云认证Token
  async getAuthToken() {
    return await tokenManager.getToken()
  }

  // 真实的华为云OCR调用
  async callRealHuaweiOCR(imageBase64) {
    const apiUrl = `${this.config.apiUrl}/v2/${this.config.projectId}/ocr/general-text`
    
    let headers = {
      'Content-Type': 'application/json'
    }
    
    const authToken = await this.getAuthToken()
    headers['X-Auth-Token'] = authToken

    let cleanImageData = imageBase64
    if (imageBase64.includes('data:image/')) {
      cleanImageData = imageBase64.split(',')[1]
    }

    const requestBody = {
      image: cleanImageData
    }

    console.log('华为云OCR请求URL:', apiUrl)
    console.log('华为云OCR请求头:', headers)
    console.log('华为云OCR请求体大小:', requestBody.image.length)

    return new Promise((resolve, reject) => {
      wx.request({
        url: apiUrl,
        method: 'POST',
        data: requestBody,
        header: headers,
        success: (response) => {
          console.log('华为云OCR响应状态码:', response.statusCode)
          console.log('华为云OCR响应头:', response.header)
          console.log('华为云OCR响应数据:', response.data)

          if (response.statusCode === 200) {
            resolve(this.parseResult(response.data))
          } else {
            const errorMessage = response.data ? JSON.stringify(response.data) : '无响应数据'
            reject(new Error(`华为云OCR请求失败: ${response.statusCode} - ${errorMessage}`))
          }
        },
        fail: (error) => {
          console.error('华为云OCR请求失败:', error)
          reject(error)
        }
      })
    })
  }

  // 解析OCR结果
  parseResult(result) {
    if (!result.result || !result.result.words_block_list) {
      console.log('华为云OCR结果为空:', result)
      return []
    }

    return result.result.words_block_list.map((item, index) => ({
      text: item.words,
      confidence: item.confidence || 0.9,
      position: {
        x: item.location?.left_top?.x || 0,
        y: item.location?.left_top?.y || 0,
        width: (item.location?.right_bottom?.x || 0) - (item.location?.left_top?.x || 0),
        height: (item.location?.right_bottom?.y || 0) - (item.location?.left_top?.y || 0)
      },
      index
    }))
  }

  // 从OCR结果中提取位置信息
  extractPositionFromOCR(item, index) {
    console.log('提取位置信息，原始数据:', item)
    
    // 华为云OCR返回的位置信息结构
    if (item.location && item.location.left_top && item.location.right_bottom) {
      const x = item.location.left_top.x || 0
      const y = item.location.left_top.y || 0
      const width = (item.location.right_bottom.x || 0) - x
      const height = (item.location.right_bottom.y || 0) - y
      
      console.log('从location提取位置:', { x, y, width, height })
      return { x, y, width, height }
    } 
    // 备用位置信息
    else if (item.boundingBox) {
      const x = item.boundingBox.x || 0
      const y = item.boundingBox.y || 0
      const width = item.boundingBox.width || 100
      const height = item.boundingBox.height || 30
      
      console.log('从boundingBox提取位置:', { x, y, width, height })
      return { x, y, width, height }
    } 
    // 生成模拟位置信息
    else {
      const row = Math.floor(index / 3)
      const col = index % 3
      const x = 50 + col * 200
      const y = 100 + row * 80
      const width = 150
      const height = 40
      
      console.log('生成模拟位置:', { x, y, width, height })
      return { x, y, width, height }
    }
  }

  // 识别口算题目
  extractMathProblems(ocrResults) {
    const mathProblems = []
    const mathPatterns = [
      /(\d+)\s*([+\-×÷])\s*(\d+)\s*=\s*(\d+)/,
      /(\d+)\s*÷\s*(\d+)\s*=\s*(\d+)(?:\.\.\.|余|余数)?(\d+)?/,
      /(\d+\/\d+)\s*([+\-×÷])\s*(\d+\/\d+)\s*=\s*(\d+\/\d+)/,
      /\((\d+\s*[+\-×÷]\s*\d+)\)\s*([+\-×÷])\s*(\d+)\s*=\s*(\d+)/,
      /(\d+\.\d+)\s*([+\-×÷])\s*(\d+\.\d+)\s*=\s*(\d+\.\d+)/,
      /(\d+)\s*([+\-×÷])\s*(\d+)\s*([+\-×÷])\s*(\d+)\s*=\s*(\d+)/
    ]

    ocrResults.forEach((item, index) => {
      let match = null
      let patternIndex = -1
      
      for (let i = 0; i < mathPatterns.length; i++) {
        match = item.text.match(mathPatterns[i])
        if (match) {
          patternIndex = i
          break
        }
      }

      if (match) {
        let problem = null
        const position = this.extractPositionFromOCR(item, index)
        
        switch (patternIndex) {
          case 0:
            problem = {
              type: 'basic',
              question: `${match[1]} ${match[2]} ${match[3]} = ${match[4]}`,
              num1: parseFloat(match[1]),
              operator: match[2],
              num2: parseFloat(match[3]),
              userAnswer: parseFloat(match[4]),
              confidence: item.confidence,
              position: position
            }
            break
            
          case 1:
            problem = {
              type: 'division_with_remainder',
              question: `${match[1]} ÷ ${match[2]} = ${match[3]}${match[4] ? (match[1].includes('余') ? '余' : '...') + match[4] : ''}`,
              dividend: parseFloat(match[1]),
              divisor: parseFloat(match[2]),
              quotient: parseFloat(match[3]),
              remainder: match[4] ? parseFloat(match[4]) : 0,
              userAnswer: { quotient: parseFloat(match[3]), remainder: match[4] ? parseFloat(match[4]) : 0 },
              confidence: item.confidence,
              position: position
            }
            break
            
          case 2:
            problem = {
              type: 'fraction',
              question: `${match[1]} ${match[2]} ${match[3]} = ${match[4]}`,
              fraction1: this.parseFraction(match[1]),
              operator: match[2],
              fraction2: this.parseFraction(match[3]),
              userAnswer: this.parseFraction(match[4]),
              confidence: item.confidence,
              position: position
            }
            break
            
          case 3:
            problem = {
              type: 'parentheses',
              question: `(${match[1]}) ${match[2]} ${match[3]} = ${match[4]}`,
              innerExpression: match[1],
              operator: match[2],
              num2: parseFloat(match[3]),
              userAnswer: parseFloat(match[4]),
              confidence: item.confidence,
              position: position
            }
            break
            
          case 4:
            problem = {
              type: 'decimal',
              question: `${match[1]} ${match[2]} ${match[3]} = ${match[4]}`,
              num1: parseFloat(match[1]),
              operator: match[2],
              num2: parseFloat(match[3]),
              userAnswer: parseFloat(match[4]),
              confidence: item.confidence,
              position: position
            }
            break
            
          case 5:
            problem = {
              type: 'mixed',
              question: `${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]} = ${match[6]}`,
              num1: parseFloat(match[1]),
              operator1: match[2],
              num2: parseFloat(match[3]),
              operator2: match[4],
              num3: parseFloat(match[5]),
              userAnswer: parseFloat(match[6]),
              confidence: item.confidence,
              position: position
            }
            break
        }
        
        if (problem) {
          mathProblems.push(problem)
        }
      }
    })

    return mathProblems
  }

  // 解析分数
  parseFraction(fractionStr) {
    const parts = fractionStr.split('/')
    return {
      numerator: parseFloat(parts[0]),
      denominator: parseFloat(parts[1])
    }
  }

  // 计算正确答案
  calculateCorrectAnswer(problem) {
    try {
      switch (problem.type) {
        case 'basic':
          return this.calculateBasicOperation(problem.num1, problem.operator, problem.num2)
        case 'division_with_remainder':
          return this.calculateDivisionWithRemainder(problem.dividend, problem.divisor)
        case 'fraction':
          return this.calculateFractionOperation(problem.fraction1, problem.operator, problem.fraction2)
        case 'parentheses':
          return this.calculateParenthesesExpression(problem.innerExpression, problem.operator, problem.num2)
        case 'decimal':
          return this.calculateBasicOperation(problem.num1, problem.operator, problem.num2)
        case 'mixed':
          return this.calculateMixedOperation(problem.num1, problem.operator1, problem.num2, problem.operator2, problem.num3)
        default:
          return null
      }
    } catch (error) {
      console.error('计算正确答案时出错:', error)
      return null
    }
  }

  // 基本四则运算
  calculateBasicOperation(num1, operator, num2) {
    switch (operator) {
      case '+': return num1 + num2
      case '-': return num1 - num2
      case '×': return num1 * num2
      case '÷': return num2 !== 0 ? num1 / num2 : null
      default: return null
    }
  }

  // 带余数的除法
  calculateDivisionWithRemainder(dividend, divisor) {
    if (divisor === 0) return null
    const quotient = Math.floor(dividend / divisor)
    const remainder = dividend % divisor
    return { quotient, remainder }
  }

  // 分数运算
  calculateFractionOperation(fraction1, operator, fraction2) {
    const { numerator: num1, denominator: den1 } = fraction1
    const { numerator: num2, denominator: den2 } = fraction2
    
    switch (operator) {
      case '+':
        const sumNum = num1 * den2 + num2 * den1
        const sumDen = den1 * den2
        return this.simplifyFraction(sumNum, sumDen)
      case '-':
        const diffNum = num1 * den2 - num2 * den1
        const diffDen = den1 * den2
        return this.simplifyFraction(diffNum, diffDen)
      case '×':
        const productNum = num1 * num2
        const productDen = den1 * den2
        return this.simplifyFraction(productNum, productDen)
      case '÷':
        if (num2 === 0) return null
        const quotientNum = num1 * den2
        const quotientDen = den1 * num2
        return this.simplifyFraction(quotientNum, quotientDen)
      default:
        return null
    }
  }

  // 简化分数
  simplifyFraction(numerator, denominator) {
    const gcd = this.greatestCommonDivisor(Math.abs(numerator), Math.abs(denominator))
    return {
      numerator: numerator / gcd,
      denominator: denominator / gcd
    }
  }

  // 最大公约数
  greatestCommonDivisor(a, b) {
    return b === 0 ? a : this.greatestCommonDivisor(b, a % b)
  }

  // 带括号的表达式计算
  calculateParenthesesExpression(innerExpr, operator, num2) {
    const innerMatch = innerExpr.match(/(\d+)\s*([+\-×÷])\s*(\d+)/)
    if (innerMatch) {
      const innerResult = this.calculateBasicOperation(
        parseFloat(innerMatch[1]), 
        innerMatch[2], 
        parseFloat(innerMatch[3])
      )
      if (innerResult !== null) {
        return this.calculateBasicOperation(innerResult, operator, num2)
      }
    }
    return null
  }

  // 混合运算
  calculateMixedOperation(num1, operator1, num2, operator2, num3) {
    let result
    
    if (operator1 === '×' || operator1 === '÷') {
      result = this.calculateBasicOperation(num1, operator1, num2)
      if (result === null) return null
      return this.calculateBasicOperation(result, operator2, num3)
    } else if (operator2 === '×' || operator2 === '÷') {
      result = this.calculateBasicOperation(num2, operator2, num3)
      if (result === null) return null
      return this.calculateBasicOperation(num1, operator1, result)
    } else {
      result = this.calculateBasicOperation(num1, operator1, num2)
      if (result === null) return null
      return this.calculateBasicOperation(result, operator2, num3)
    }
  }

  // 批改口算题目
  gradeMathProblems(problems) {
    return problems.map(problem => {
      const correctAnswer = this.calculateCorrectAnswer(problem)
      let isCorrect = false
      let answerComparison = ''
      
      if (correctAnswer !== null) {
        switch (problem.type) {
          case 'division_with_remainder':
            isCorrect = problem.userAnswer.quotient === correctAnswer.quotient && 
                       problem.userAnswer.remainder === correctAnswer.remainder
            answerComparison = `商: ${correctAnswer.quotient}, 余数: ${correctAnswer.remainder}`
            break
          case 'fraction':
            isCorrect = problem.userAnswer.numerator === correctAnswer.numerator && 
                       problem.userAnswer.denominator === correctAnswer.denominator
            answerComparison = `${correctAnswer.numerator}/${correctAnswer.denominator}`
            break
          default:
            isCorrect = problem.userAnswer === correctAnswer
            answerComparison = correctAnswer.toString()
        }
      }
      
      return {
        id: problem.position?.index || Math.random(),
        type: problem.type,
        question: problem.question,
        userAnswer: problem.userAnswer,
        correctAnswer: correctAnswer,
        answerComparison: answerComparison,
        isCorrect: isCorrect,
        confidence: problem.confidence,
        position: problem.position
      }
    })
  }
}

module.exports = new HuaweiOCRService()
